<template>
  <div class="Server">
    <el-row>
      <!-- 头部2，创建按钮 及搜索框 -->
      <el-col :span="24">
        <el-card class="Server-head-card" shadow="never" :body-style="{padding:'10px'}">
          <!-- float属性，会将多个同级标签放在同一行 -->
          <div style="float: left;margin-right:10px;">
            <el-button  size="small" type="primary" icon="Edit"  @click="createserverDrawer = true">创建</el-button>
          </div>
          <div>
            <el-input class="Server-head-search" size="small" clearable placeholder="请输入" v-model='searchValue'></el-input>
                        <el-button size="small" type="primary" plain icon="Edit" @click="getServers()">搜索</el-button>

          </div>
        </el-card>
      </el-col>
      <el-col :span="24">
        <div>
          <el-card class="Server-body-card" shadow="never" :body-style="{padding:'5px'}">
            <el-table
                style="width:100%;font-size:12px;margin-bottom:10px;"
                :data="ServerList"
                v-loading="appLoading">
              <el-table-column width="20"></el-table-column>


              <el-table-column align=center min-width="120" label="服务器主机名">
                <template v-slot="scope">
                  <el-tag type="info">{{ scope.row.hostname }} </el-tag>
                </template>
              </el-table-column>

              <el-table-column align=center min-width="100" label="公网IP地址">
                <template v-slot="scope">
                  <el-tag type="info">{{ scope.row.public_ip }} </el-tag>
                </template>
              </el-table-column>


              <el-table-column align=center min-width="100" label="内网IP地址">
                <template v-slot="scope">
                  <!--                              <el-tag type="info">{{ scope.row.private_ip }} </el-tag>-->
                  <el-tag v-for="(item, index) in scope.row.private_ip" :key="index" type="info">
                    <!--                                {{ item.ip_name }}-->
                    {{ item.ip }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column align=center min-width="100" label="硬盘容量">
                <template v-slot="scope">
                  <!--                              <el-tag type="info">{{ scope.row.disk }} </el-tag>-->
                  <el-tag v-for="(item, index) in scope.row.disk" :key="index" type="info">
                    {{ item.device }} - {{ item.size }}
                  </el-tag>
                </template>
              </el-table-column>
              <!--                          <el-table-column align=center min-width="100" label="主机类型">-->
              <!--                            <template v-slot="scope">-->
              <!--                              <el-tag type="info">{{ scope.row.machine_type }} </el-tag>-->
              <!--                            </template>-->
              <!--                          </el-table-column>-->
              <el-table-column align=center min-width="80" label="CPU">
                <template v-slot="scope">
                  <el-tag type="info">{{ scope.row.cpu_num }} </el-tag>
                </template>
              </el-table-column>
              <el-table-column align=center min-width="80" label="内存">
                <template v-slot="scope">
                  <el-tag type="info">{{ scope.row.memory }} </el-tag>
                </template>
              </el-table-column>
              <el-table-column align=center min-width="100" label="创建时间">
                <template v-slot="scope">
                  <el-tag type="info">{{ scope.row.put_shelves_date }} </el-tag>
                </template>
              </el-table-column>

              <el-table-column align=left label="服务器组">
                <template v-slot="scope">
                  <div v-for="server in scope.row.HostGroups" :key="server.id">
                    {{ server.group_name }}
                  </div>
                </template>
              </el-table-column>

              <el-table-column align=left label="凭据">
                <template v-slot="scope">
                  <div v-for="credential in scope.row.Credentials" :key="credential.id">
                    {{ credential.name }}
                  </div>
                </template>
              </el-table-column>


              <el-table-column align=center label="操作" min-width="150">
                <template v-slot="scope">
                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="primary" plain @click="SSH(scope.$index, scope.row)" >连接</el-button>
                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="primary" plain @click="sync(scope)">同步</el-button>
                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="primary" plain @click="modify_data(scope,updataserverFunc)">修改</el-button>
                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="danger"  plain @click="handleConfirm(scope, '删除', delServer )">删除</el-button>
                </template>
              </el-table-column>

            </el-table>
            <el-pagination
                class="Server-body-pagination"
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="pagesizeList"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :prev-click="getServers"
                :total="ServerTotal">
            </el-pagination>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <!-- 创建 -->
    <el-drawer
        v-model="createserverDrawer"
        direction="rtl"
        :before-close="handleClose"
        title="创建服务器">
      <template #default>
        <!-- flex布局,居中 -->
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <!-- ref绑定控件后，js中才能用this.$ref获取该控件 -->
            <!-- rules 定义form表单校验规则 -->
            <el-form ref="createserverData" :rules="createserverRules" :model="createserverData" label-width="80px">
              <!-- prop用于rules中的校验规则的key -->
              <el-form-item class="deploy-create-form" label="服务器IP地址" prop="ip">
                <el-input v-model="createserverData.ip"></el-input>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="服务器端口" prop="post">
                <el-input v-model="createserverData.post"></el-input>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="执行命令(默认)" prop="command">
                <el-input v-model="createserverData.command"></el-input>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="服务器组" prop="group_name">
                <el-select v-model="ServergroupList.group_name" filterable placeholder="请选择">
                  <el-option
                      v-for="(item, index) in ServergroupList"
                      :key="index"
                      :label="item.group_name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <div style="margin-top: 20px">
                <el-radio-group v-model="authentication">
                  <el-radio label="1" border>临时登入</el-radio>
                  <el-radio label="2" border>秘钥对</el-radio>
                </el-radio-group>
              </div>

              <!-- 服务器账号和密码表单项 -->
              <el-form-item class="deploy-create-form" label="服务器账号" prop="user" v-if="authentication === '1'">
                <el-input v-model="createserverData.user"></el-input>
              </el-form-item>
              <el-form-item class="deploy-create-form" label="服务器密码" prop="password" v-if="authentication === '1'">
                <el-input v-model="createserverData.password"></el-input>
              </el-form-item>

              <!-- 凭据选择表单项 -->
              <el-form-item class="deploy-create-form" label="凭据选择" prop="name" v-if="authentication === '2'">
                <el-select v-model="CredentialList.name" filterable placeholder="请选择">
                  <el-option
                      v-for="(item, index) in CredentialList"
                      :key="index"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>


            </el-form>
          </el-col>
        </el-row>
      </template>
      <!-- 插槽，抽屉footer -->
      <template #footer>
        <!-- 点击后赋值false，隐藏抽屉 -->
        <el-button @click="createserverDrawer=false">取消</el-button>
        <!--        <el-button type="primary" @click="createserverFunc()">立即创建</el-button>-->
        <el-button type="primary" @click="submitForm('createserverData')">立即创建</el-button>

      </template>
    </el-drawer>

    <!-- 修改 -->
    <el-drawer
        v-model="updataserverDrawer"
        direction="rtl"
        :before-close="handleClose"
        title="修改服务器">
      <template #default>
        <!-- flex布局,居中 -->
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <!-- ref绑定控件后，js中才能用this.$ref获取该控件 -->
            <!-- rules 定义form表单校验规则 -->
            <el-form ref="updateServerData"  :model="updateServerData" label-width="80px">
              <!-- prop用于rules中的校验规则的key -->

              <el-form-item class="deploy-create-form" label="选择服务器组" prop="namespace">
                <el-select v-model="ServergroupList.group_name" filterable placeholder="请选择">
                  <el-option
                      v-for="(item, index) in ServergroupList"
                      :key="index"
                      :label="item.group_name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

            </el-form>
          </el-col>
        </el-row>
      </template>
      <!-- 插槽，抽屉footer -->
      <template #footer>
        <!-- 点击后赋值false，隐藏抽屉 -->
        <el-button @click="updataserverDrawer=false">取消</el-button>
        <el-button type="primary" @click="updataserverFunc()">确定</el-button>
      </template>
    </el-drawer>
  </div>

  <SSH v-model:visible="sshDialogVisible" :row="currentRow" ></SSH>
</template>

<script>
import common from "../../common/Config";
import httpClient from '@/request';
import SSH from "@/views/cmdb/servers/SSH";

export default {
  data() {
    return {
      //编辑器配置
      cmOptions: common.cmOptions,
      contentYaml: '',
      //分页
      currentPage: 1,
      pagesize: 10,
      pagesizeList: [10, 20, 30],
      searchValue: '',
      appLoading: false,
      authentication:'',
      //服务器组列表
      ServergroupList: [],
      getServersgroupData: {
        url: common.servergroupList,
        HostServers:'',
      },

      //凭据列表
      CredentialList: [],
      getCredentialData: {
        url: common.credentialList,
        name:'',
      },

      //接口详情
      hostGroupName: '',
      getServersgroupDetail: {
        url: common.servergrouplDetail,
      },


      //查询服务器列表
      ServerList: [],
      ServerTotal: 0,
      getServersData: {
        url: common.serverList,
        params: {
          hostname: '',
          public_ip: '',
          private_ip: '',
          os_version: '',
          disk: '',
          machine_type: '',
          cpu_num: '',
          memory: '',
          put_shelves_date: '',
          ssh_ip:'',
          ssh_port:'',
          hostgroupID:'',
          page: '',
          limit: '',
        }
      },
      //新增
      createserverDrawer: false,
      createserverData: {
        url: common.serverAdd,
        user: 'root',
        password: '123123',
        ip:'192.168.43.197',
        post:'22',
        command:'python3 /tmp/servermain.py',
        hostgroupID:'',
        credentialID:'',
        name: [],  //CredentialList列表后面优化名称
        ServergroupList: [],
      },
      //创建server的表单校验规则
      createserverRules: {
        ip: [{
          required: true,
          message: '请填写密码',
          trigger: 'change'
        }],
        post: [{
          required: true,
          message: '请填写密码',
          trigger: 'change'
        }],
        user: [{
          required: true,
          message: '请填写账号',
          trigger: 'change'
        }],
        password: [{
          required: true,
          message: '请填写密码',
          trigger: 'change'
        }],
        //CredentialList列表名称后面优化名称
        name: [{
          required: true,
          message: '请填写凭据',
          trigger: 'change'
        }],
      },


      //修改
      updataserverDrawer: false,
      updateServerData: {
        url: common.serverUpdate,
        updategroupID:'',

      },

      //同步
      syncdata: {
          url: common.syncdate,
          serverid:'',
          user:'',
          password:'',
          ssh_ip:'',
        ssh_post:'',
          credentialID:'',
      },
      //删除
      delServerData: {
        url: common.serverDelete,
        params: {
          id:'',
          Server_name: '',
        }
      },
      currentRow: '',  //将数据传递给子组件
      sshDialogVisible: false,
    }
  },
  methods: {
    //创建
    createserverFunc() {
      //赋值
      this.createserverData.hostgroupID = this.ServergroupList.group_name
      this.createserverData.credentialID = this.CredentialList.name
      console.log(this.createserverData)
      httpClient.post(this.createserverData.url, this.createserverData)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
          .finally(() => {
            this.getServers()
            this.createserverDrawer = false
            this.appLoading = false
          })
    },
    //提交表单，验证数据
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        console.log(this.$refs[formName])
        if (valid) {
          this.createserverFunc()
        } else {
          return false
        }
      })
    },

    //读取servergroup列表
    servergroup() {
      console.log(this.getServersgroupData)
      httpClient.get(this.getServersgroupData.url)
          .then(res => {
            this.ServergroupList = res.data
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    //读取credential列表
    credential() {
      console.log(this.getCredentialData)
      httpClient.get(this.getCredentialData.url)
          .then(res => {
            this.CredentialList = res.data
            this.createserverData.name = res.data
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    //修改
    modify_data(e) {
      this.updataserverDrawer = true
      //赋值获取当前服务器ID
      this.updateServerData.id= e.row.id
    },

    updataserverFunc() {
      //赋值需要服务器组ID
      this.updateServerData.updategroupID = this.ServergroupList.group_name
      httpClient.put(this.updateServerData.url, this.updateServerData)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
          .finally(() => {
            this.getServers()
            this.updataserverDrawer = false
            this.appLoading = false
          })
      console.log(this.updateServerData)
    },

    sync(e){
      //赋值
      this.syncdata.serverid = e.row.id
      this.syncdata.ssh_ip = e.row.ssh_ip
      // this.syncdata.sship = "1.1.1.1"
      // this.syncdata.sshport = "222"
      this.syncdata.ssh_post = e.row.ssh_port
      this.syncdata.credentialID = e.row.Credentials[0].id
      this.syncdata.user = e.row.Credentials[0].user
      this.syncdata.password = e.row.Credentials[0].password

      httpClient.post(this.syncdata.url,  this.syncdata)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })

          })
          .finally(() => {
            this.getServers()
          })
      console.log(this.syncdata)
    },

    getServers() {
      this.appLoading = true
      this.getServersData.params.page = this.currentPage
      this.getServersData.params.limit = this.pagesize
      httpClient.get(this.getServersData.url, {params: this.getServersData.params})
          .then(res => {
            this.ServerList = res.data
            this.ServerTotal = res.data.total
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
      this.appLoading = false
    },

    delServer(e) {
      this.delServerData.params.id = e.row.id
      httpClient.delete(this.delServerData.url, {data: this.delServerData.params})
          .then(res => {
            this.getServers()
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    //分页属性
    handleSizeChange(size) {
      this.pagesize = size;
      this.getServers()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getServers()
    },
    //选择判断
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(() => {
            done();
          })
          .catch(() => {});
    },


    handleConfirm(obj, operateName, fn) {
      this.confirmContent = '确认继续 ' + operateName + ' 操作吗？'
      this.$confirm(this.confirmContent,'提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
          .then(() => {
            fn(obj)
          })
          .catch(() => {
            this.$message.info({
              message: '已取消操作'
            })
          })
    },
    SSH(index, row) {
      this.currentRow = row;
      console.log(this.currentRow)
      this.sshDialogVisible = true;
    },
  },
  //注册子组件
  components: {
    SSH,
  },


  //beforeMount() {
  mounted() {
    this.getServers()
    this.servergroup()
    this.credential()
  }
}
</script>


<style scoped>
.Server-head-card,.Server-body-card {
  border-radius: 10px;
  margin-bottom: 20px;
}
.Server-head-search {
  width:160px;
  margin-right:10px;
}
.Server-body-Servername {
  margin: 0px;
  color: #4795EE;
}
.Server-body-ip {
  margin: 0px;
  color: rgb(145, 145, 145);
}
.Server-body-Servername:hover {
  color: rgb(84, 138, 238);
  cursor: pointer;
  font-weight: bold;
}
</style>